package bunchBridgeTests;



import static org.junit.Assert.assertArrayEquals;
import static org.junit.Assert.assertTrue;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileWriter;

import org.junit.Before;
import org.junit.Test;

import primitives.cluster.ClusterHead;
import bunch.ClusterFileParser;
import bunch.DependencyFileParser;
import bunchbridge.GraphConverter;

public class GraphConverterTest {
	private primitives.graph.Graph g;
	private primitives.cluster.ClusterHead ch;
	private bunch.Graph bunchG;
	private bunch.Graph clusteredG;

	@Before
	public void setUp() throws Exception {
		g = new primitives.graph.Graph();
		primitives.graph.Node[] nodes = { new primitives.graph.Node("a"),
				new primitives.graph.Node("b"), new primitives.graph.Node("c"),
				new primitives.graph.Node("d") };
		for (primitives.graph.Node n : nodes) {
			g.addNode(n);

		}
		g.connect(nodes[0], nodes[1]);
		g.connect(nodes[1], nodes[2]);
		g.connect(nodes[2], nodes[3]);
		g.connect(nodes[0], nodes[3]);

		// Create temp file.
		File temp = File.createTempFile("bunchTest", ".mdg");

		// Delete temp file when program exits.
		temp.deleteOnExit();

		// Write to temp file
		BufferedWriter out = new BufferedWriter(new FileWriter(temp));
		out.write("a b" + "\nb c" + "\nc d" + "\na d");
		out.close();

		DependencyFileParser parser = new DependencyFileParser();
		parser.setInput(temp.getAbsolutePath());
		bunchG = (bunch.Graph) parser.parse();

		File silFile = File.createTempFile("bunchTest", ".sil");
		silFile.deleteOnExit();
		BufferedWriter silOut = new BufferedWriter(new FileWriter(temp));
		silOut.write("SS(SS-L0:1)=a\n" + "SS(SS-L0:2_4)=b\n"
				+ "SS(SS-L0:3)=c\n" + "SS(SS-L0:5)=d\n");
		silOut.close();

		ClusterFileParser cfp = new ClusterFileParser();

		cfp.setInput(silFile.getAbsolutePath());
		cfp.setObject(bunchG);
		cfp.parse();

		clusteredG = bunchG;
		ch = new ClusterHead(g);
	}

	@Test
	public void testConvertToBunchGraph() {

		bunch.Graph converted = GraphConverter.convertToBunchGraph(g);

		for (bunch.Node n : converted.getNodes()) {
			boolean found = false;
			for (bunch.Node orign : bunchG.getNodes()) {
				if (n.getId() == orign.getId()) {
					found = true;
				}
			}
			assertTrue("Node " + n.getId() + " found?", found);
		}

		for (bunch.Node n : converted.getNodes()) {
			boolean found = false;
			for (bunch.Node orign : bunchG.getNodes()) {
				if (n.getName().equals(orign.getName())) {
					found = true;
				}
			}
			assertTrue("Node " + n.getName() + " found?", found);
		}

	}

	@Test
	public void testConvertToBunchCluster() {
		bunch.Graph clusteredConversion = GraphConverter
				.convertToBunchCluster(ch);
		assertArrayEquals(clusteredConversion.getClusters(), clusteredG
				.getClusters());
	}

}
